import logging
import os
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import (NoSuchElementException, TimeoutException, ElementNotVisibleException, InvalidSelectorException)
from selenium.webdriver.support.select import Select
from selenium.common.exceptions import UnexpectedTagNameException
class Base:
    def __init__(self,driver):
        self.driver=driver
    def get(self,url):
        self.driver.get(url)
    def find_element(self,loc):

        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver:self.driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except NoSuchElementException as e:
            # 未找到元素异常
            # 生成时间
            error_time=time.strftime('%Y-%m-%d %H-%M-%S')
            # 报错截屏目录
            screenshot_dir=r"D:\ghs_pycharm\longguo_payment_ui_auto_test\ERROR_save"
            # 拼接完整路径
            screenshot_path=os.path.join(screenshot_dir,f"{error_time}未找到元素异常.png")
            print('未找到符合定位符的元素',e)
            # 保存截图
            self.driver.save_screenshot(screenshot_path)
        except TimeoutException as timeout:
            # 超时异常
            # 生成时间
            error_time = time.strftime('%Y-%m-%d %H-%M-%S')
            # 报错截屏目录
            screenshot_dir = r"D:\ghs_pycharm\longguo_payment_ui_auto_test\ERROR_save"
            # 拼接完整路径
            screenshot_path = os.path.join(screenshot_dir, f"{error_time}超时.png")
            print('超时', timeout)
            # 保存截图
            self.driver.save_screenshot(screenshot_path)
        except ElementNotVisibleException as element:
            # 元素不可见异常
            # 生成时间
            error_time = time.strftime('%Y-%m-%d %H-%M-%S')
            # 报错截屏目录
            screenshot_dir = r"D:\ghs_pycharm\longguo_payment_ui_auto_test\ERROR_save"
            # 拼接完整路径
            screenshot_path = os.path.join(screenshot_dir, f"{error_time}元素不可见.png")
            print('无法交互', element)
            # 保存截图
            self.driver.save_screenshot(screenshot_path)
        except InvalidSelectorException as invalid:
            # 无效选择器异常
            # 生成时间
            error_time = time.strftime('%Y-%m-%d %H-%M-%S')
            # 报错截屏目录
            screenshot_dir = r"D:\ghs_pycharm\longguo_payment_ui_auto_test\ERROR_save"
            # 拼接完整路径
            screenshot_path = os.path.join(screenshot_dir, f"{error_time}语法错误.png")
            print('语法错误', invalid)
            # 保存截图
            self.driver.save_screenshot(screenshot_path)

    def click(self,loc):
        self.find_element(loc).click()
    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)
    def frame(self,loc):
        self.driver.switch_to.frame(self.find_element(loc))
    def select_by(self,loc,by,value=None):
        try:
            select_elem=self.find_element(loc)

            select=Select(select_elem)

            if by=='text':
                select.select_by_visible_text(value)
            elif by=='value':
                select.select_by_value(value)
            elif by=='index':
                select.select_by_index(value)
        except UnexpectedTagNameException:
            print(f"元素不是select标签：{loc}")
        except Exception as e:
            print(f'下拉选择失败：{loc}，方式：{by}，值：{value}')
            raise
    def handle_custom_alert(self,confirm_loc=None,cancel_loc=None,action='confirm'):
        try:
            if action=='confirm' and confirm_loc:
                self.click(confirm_loc)
            elif action=='cancel' and cancel_loc:
                self.click(cancel_loc)
        except Exception as e:
            print(f'自定义弹窗处理失败：{action}',e)
            raise


    def handle_alert(self,action='accept',text=None):
        try:
            alert=WebDriverWait(self.driver,10).until(
                lambda d:self.driver.switch_to.alert
            )
            if text:
                alert.send_keys(text)
            if action=='accept':
                alert.accept()
            else:
                alert.dismiss()
            self.driver.switch_to.default_content()
        except TimeoutException:
            # 抛出异常，触发后续的异常处理（如截图、日志、终止用例）
            raise Exception("未找到弹窗，原因：弹窗超时")
        except Exception as e:
            print(f'原生弹窗处理失败：操作{action}',e)
            raise

    def mouse_hover(self,loc):
        try:
            elem=self.find_element(loc)
            ActionChains(self.driver).move_to_element(elem).perform()
            logging.info(f"悬停成功：{loc}")
        except Exception as e:
            print(f'悬停失败：{loc}',e)
    def right_click(self,loc):
        try:
            elem=self.find_element(loc)
            ActionChains(self.driver).context_click(elem).perform()
            logging.info(f'右键点击成功：{loc}')
        except Exception as e:
            print(f"点击失败：{loc}",e)

    def drag_drop(self,source_loc,target_loc):
        try:
            source=self.find_element(source_loc)
            target=self.find_element(target_loc)
            ActionChains(self.driver).drag_and_drop(source, target).perform()
            logging.info(f'拖拽成功从{source_loc}到{target_loc}')
        except Exception as e:
            print(f"拖拽失败",e)
    def time(self,x):
        time.sleep(x)

    def get_element_text(self, loc):
        element = self.find_element(loc)  # 调用上面的查找方法
        if element:
            return element.text  # 返回元素的文本
        else:
            return f"元素 {loc} 未找到，无法获取文本"